package com.qingke.Qiximybatis.business;

import java.util.regex.Pattern;
import org.apache.ibatis.session.SqlSession;

import com.qingke.Qiximybatis.QixiApp;
import com.qingke.Qiximybatis.QixiConsole;
import com.qingke.Qiximybatis.QixiDao;
import com.qingke.Qiximybatis.command.SystemCommand;
import com.qingke.Qiximybatis.mapper.MyUserMapper;
import com.qingke.Qiximybatis.sqlclass.MyUser;

public class Register extends SystemCommand{

	@Override
	public void execute() {
		
		SqlSession session = QixiDao.mybatisSession();
		String username = null;
		String post = null;
		QixiConsole.println("欢迎来到注册界面：");
		while(true){
			post = QixiConsole.askUserInput("请输入你的电话号码：>");
			MyUserMapper myUserMapper = session.getMapper(MyUserMapper.class);	//实现MyUserMapper接口和MyUserMapper.xml文件联系起来返回接口的对象
			MyUser user = myUserMapper.getphone(post);							//目的：调用接口中的方法。
			
			if(user!=null){
				System.out.println("账户已被创建！");
			}else {
				System.out.println("该账户不存在，可以使用！");
				break;
			}
		}
		
		while(true){
			username = QixiConsole.askUserInput("请输入你的密码！>");
			Pattern lenPattern = Pattern.compile("[0-9a-zA-Z]{6,}");
			Pattern numPattern = Pattern.compile("[0-9]");
			Pattern wordPattern = Pattern.compile("[a-zA-Z]");
			if(!lenPattern.matcher(username).find()){
				System.out.println("密码长度必需大于等于6位!");
			}else if(!numPattern.matcher(username).find()){
				System.out.println("密码至少需要含有一位数字!");
			}else if(!wordPattern.matcher(username).find()){
				System.out.println("密码至少需要含有一位字母!");
			}else {
				System.out.println("密码符合要求!");
				break;
			}
		}
		registerUp(post,username);
	}
	
	
	public static void registerUp(String post,String username){
		SqlSession session = QixiDao.mybatisSession();
		MyUser myuser = new MyUser();
		System.out.println("请完善你的信息：");
		String name = QixiConsole.askUserInput("请输入昵称：>");
		String age = QixiConsole.askUserInput("请输入年龄:>");
		String height = QixiConsole.askUserInput("请输入身高:>");
		String gender=null;
		while(true){
			gender = QixiConsole.askUserInput("请输入性别：F(女)/M(男):>");
			if(gender.equalsIgnoreCase("F")&&gender.equalsIgnoreCase("M")){
				System.out.println("输入内容不正确，请重新输入！");
			}else{
				break;
			}
		}
		try{
			myuser.setUsername(username);
			myuser.setName(name);
			myuser.setGender(gender);
			myuser.setHeight(height);
			myuser.setPhone(post);
			myuser.setAge(age);
			MyUserMapper myUserMapper = session.getMapper(MyUserMapper.class);
			myUserMapper.insert(myuser);
			session.commit();
			System.out.println("新用户创建成功！");
		}finally{
			session.close();
		}
	}
	
}
